package org.scboy.dbms.sftp;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

import org.scboy.utils.entitys.coobi.Model;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import cn.hutool.core.convert.Convert;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class SshClient {
	
	Log log=LogFactory.get();
	
	 /**
     * 会话
     */
    private Session sshSession = null;
    
    public SshClient(String ip, int port, String username, String password) {
        this.connect(ip, port, username, password);
    }
    
	private Session connect(String ip, int port, String username, String password){
        JSch jsch = new JSch();
        Properties sshConfig = new Properties();
        try {
            sshSession = jsch.getSession(username, ip, port);
            sshSession.setPassword(password);
 
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            log.info("Ssh服务器连接成功!");
        }catch (Exception e){
            //log.error("Ssh连接错误: {}@{}:{}; pwd:{}", username, ip, port, password);
            throw new RuntimeException("Ssh连接错误");
        }
        return sshSession;
    }
	
	@SuppressWarnings("resource")
	public String exeCommand(String command) {
		ChannelExec channelExec;
		try {
			channelExec = (ChannelExec) sshSession.openChannel("exec");
		} catch (JSchException e) {
			throw new RuntimeException(e);
		}
		channelExec.setCommand(command);
		channelExec.setErrStream(System.err);
		try (InputStream in = channelExec.getInputStream()) {
			channelExec.connect();
			Scanner scanner = new Scanner(in).useDelimiter("\\A");
            String output = scanner.hasNext() ? scanner.next() : "";
			channelExec.disconnect();
			return output.trim();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
    public  void close() {
        if(null != sshSession){
            sshSession.disconnect();
        }
    }
    
    /**
     * 获取内存
     * @return
     */
    public Model getMem() {
		String mem=this.exeCommand("free -m | awk '/Mem/{print $2,$3,$4,$6}'");
		String [] menus=mem.split(" ");
		Model memModel=Model.create();
		memModel.add("total",Convert.toLong(menus[0]));
		memModel.add("used",Convert.toLong(menus[1]));
		memModel.add("free",Convert.toLong(menus[2]));
		memModel.add("buffCache",Convert.toLong(menus[3]));
		return memModel;
    }
    
    /**
     * 获取磁盘信息
     * @return
     */
    public List<Model> getDisk(){
    	List<Model> result=new ArrayList<Model>();
    	String disk=this.exeCommand("df -m");
    	String [] diskLine= disk.split("\n");
    	for (int i=1;i<diskLine.length;i++) {
			String [] diskinfo=diskLine[i].split("[\\s]+");
			Model diskModel=Model.create();
			diskModel.add("fileSystem", diskinfo[0]);
			diskModel.add("size", diskinfo[1]);
			diskModel.add("used", diskinfo[2]);
			diskModel.add("avail", diskinfo[3]);
			diskModel.add("use", diskinfo[4]);
			diskModel.add("mounted", diskinfo[5]);
			result.add(diskModel);
		}
    	return result;
    }
    
    /**
     * 获取CPU占用率
     * @return
     */
    public double getCpu() {
    	String cpu= this.exeCommand("top -bn1 | grep \"Cpu(s)\" | awk '{split($0,arr,\" \");print 100-arr[8]}'");
    	return Convert.toDouble(cpu);
    }
    
    public static void main(String[] args) {
		SshClient client=new SshClient("192.168.56.2", 22, "root", "root");
		client.exeCommand("shutdown -r now");
		client.close();
	}
}
